<?php

namespace App\Common\WX\Api;


use App\Common\Log;
use XWX\Common\H;
use XWX\Common\WebClient\WebClient;

/**
 * 小程序
 *
 * Class MiniProgram
 * @package App\Common\WX\Api
 */
class MiniProgram extends ApiBase
{
    /**
     * 获取用户信息
     *
     * @param $code
     * @return \XWX\Common\XReturn
     * @throws \Exception
     */
    public function funcGetUserInfo($code)
    {
        $api_url = $this->funcGetApiUrl('sns/jscode2session');

        $data = [
            'appid' => $this->config()->app_id,
            'secret' => $this->config()->app_secret,
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];
        $string1 = H::funcStrQueryFromArray($data);

        $url = "{$api_url}?{$string1}";
        $r = $this->funcApi($url);

//        if ($r->ok())
//        {
//            $r->getData('openid');
//            $r->getData('session_key');
//        }


        return $r;
    }


    /**
     * 解密接口返回的数据
     *
     * @param $session_key
     * @param $iv
     * @param $encrypted_data
     * @return array
     * @throws \Exception
     */
    public function funcDecryptData($session_key, $iv, $encrypted_data)
    {
        $aes_session_key = base64_decode($session_key);
        $aes_iv = base64_decode($iv);
        $aes_encrypted_data = base64_decode($encrypted_data);


        $res = openssl_decrypt($aes_encrypted_data, "AES-128-CBC", $aes_session_key, 1, $aes_iv);
        $arr = json_decode($res, true);
        if ($arr === false)
        {
            throw new \Exception('decrypt data error');
        }

        $watermark = H::funcArrayGet($arr, 'watermark');
        $app_id = H::funcArrayGet($watermark, 'appid');
        if ($this->config()->app_id != $app_id)
        {
            throw new \Exception('app_id error');
        }


        return $arr;
    }
}